//
//  MTStrengthViewController.swift
//  MT
//
//  Created by ooops on 2020/5/14.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import JXCategoryView
import JXPagingView
import MTCategory
import YPNavigationBarTransition
import JXSegmentedView
import RxSwift
import RxCocoa

extension MTStrengthViewController: MTDiscoverRateHeaderViewDelegate {
    func didTapUserAvatar() {
        if let userName = self.headerDataModel?.userName {
            let c = MineViewController(username: userName)
            navigationController?.pushViewController(c, animated: true)
        }
    }
}

extension MTStrengthViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.listViewDidScrollCallback?(scrollView)
    }
    //MARK: UICollectionViewDataSource
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // TODO:- Required Method
        return result?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: MTStrengthCollectionViewCell.reuseIdentity(), for: indexPath) as! MTStrengthCollectionViewCell
        configureCell(cell: cell, forItemAt: indexPath)
        // TODO:- Required Method
        return cell
    }
    
    func configureCell(cell: MTStrengthCollectionViewCell, forItemAt indexPath: IndexPath) {
        let model = self.result?[indexPath.row]
        cell.model = model
        cell.discoverType = self.discoverType
        cell.rateNumber = indexPath.row + 2
        cell.disableGesture = true
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: MTDiscoverRateHeaderView.reuseIdentity(), for: indexPath) as! MTDiscoverRateHeaderView
        view.model = self.headerDataModel
        view.discoverType = self.discoverType
        view.delegate = self
        view.rateNumber = 1
        return view
    }
    
    
    //MARK: UICollectionViewDelegate
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var userName: String?
        if let model = self.result?[indexPath.row], let userName = model.userName {
            let c = MineViewController(username: userName)
            navigationController?.pushViewController(c, animated: true)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        
    }
    
}

extension MTStrengthViewController: JXSegmentedListContainerViewListDelegate {
    func listViewDidScrollCallback(callback: @escaping (UIScrollView) -> ()) {
        listViewDidScrollCallback = callback
    }


    func listView() -> UIView {
        return self.view
    }

    func listScrollView() -> UIScrollView {
        return self.collectionView
    }
}

class MTStrengthViewController: BaseViewController {
    
    public var listViewDidScrollCallback: ((UIScrollView) -> ())?

    private lazy var provider: MTProvider<MTDiscoverAPI> = {
        let provider = MTProvider<MTDiscoverAPI>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    var result: [MTRankingInfoModel]?
    
    private var headerDataModel: MTRankingInfoModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        loadData()
    }
    
    private var discoverType: MTDiscoverTableFooterViewType = MTDiscoverTableFooterViewType.strength
    
    convenience init(type: MTDiscoverTableFooterViewType) {
        self.init()
        self.discoverType = type
    }
    
    private func loadData() {
        if discoverType == .strength {
            MTDiscoverTool.strengthList(provider: provider, complete: {[weak self] (model) in
                guard let weakSelf = self else { return }
                if model?.code == 200 {
                    weakSelf.comporseDate(result: model?.result)
                }
            }) { (error) in
                
            }
        } else {
            MTDiscoverTool.charmList(provider: provider, complete: {[weak self] (model) in
                guard let weakSelf = self else { return }
                if model?.code == 200 {
                    weakSelf.comporseDate(result: model?.result)
                }
            }) { (error) in
                
            }
        }
    }
    
    private func comporseDate(result: [MTRankingInfoModel]?) {
        self.result = result
        if let r = result {
            if r.count > 0 {
                self.headerDataModel = r.first
                self.result?.removeFirst()
            }
        }
        
        DispatchQueue.main.async {
            self.collectionView.reloadData()
        }
    }
    
    lazy var collectionView: UICollectionView = {
        /// 设置大小
        let inset: CGFloat = 8
        let itemWidth = (ScreenWidth - inset * 2 - 1 - 6) / 2
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumLineSpacing = 6
        flowLayout.minimumInteritemSpacing = 6
        flowLayout.headerReferenceSize = CGSize(width: ScreenWidth, height: ScreenWidth)
        flowLayout.sectionInset = UIEdgeInsets(top: 6, left: 0, bottom: 0, right: 0)
        let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        cv.backgroundColor = UIColor.white
        cv.contentInset = UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)
        cv.showsVerticalScrollIndicator = false
        cv.delegate = self
        cv.dataSource = self
        //        cv.isPagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        /// 注册 Cell
        cv.register(MTStrengthCollectionViewCell.self, forCellWithReuseIdentifier: MTStrengthCollectionViewCell.reuseIdentity())
        cv.register(MTDiscoverRateHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: MTDiscoverRateHeaderView.reuseIdentity())
        cv.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf.loadData()

        }
        return cv
    }()
    

}
